<template>
  <div class="bh-container">
    <a-row justify="space-between" align="center" class="header page_header">
      <a-space wrap>
        <div class="title">代码生成</div>
      </a-space>
    </a-row>
    <BhTable
        row-key="name"
        :data="dataList as []"
        :columns="columns"
        :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="pagination"
        :disabled-tools="['size', 'setting']"
        :disabled-column-keys="['name']"
        @refresh="search"
    >
      <template #toolbar-left>
        <BhForm ref="formRef" :columns="queryColumns" :model-value="queryForm"
                :options="options" @search="search" @reset="reset"></BhForm>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-link v-permission="['sys:generator:config']" title="配置" @click="onConfig(record.name, record.comment)">
            代码配置
          </a-link>
          <a-link v-permission="['sys:generator:preview']" @click="onPreview(record.name)">
            一键预览
          </a-link>
          <a-link v-permission="['sys:generator:download']" @click="onGenerate(record.name)">
            下载源码
          </a-link>
        </a-space>
      </template>
    </BhTable>

    <!-- 表结构配置 -->
    <GenConfigDrawer ref="GenConfigDrawerRef" @save-success="search"/>
    <GenPreviewModal ref="GenPreviewModalRef" @generate="onGenerate"/>
  </div>
</template>

<script setup lang="ts">
import GenConfigDrawer from './GenConfigDrawer.vue'
import {getList, generate} from '@/api/system/code'
import type {TableInstanceColumns} from '@/components/BhTable'
import {useTable} from '@/hooks/modules/useTable'
import {isMobile} from '@/utils'
import {useDictStore} from "@/store";
import {type Columns, BhForm, type Options} from '@/components/BhForm'

const options: Options = {
  form: {layout: 'inline'},
  grid: {cols: {xs: 2, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4}},
  fold: {enable: false, index: 1, defaultCollapsed: true},
}
const queryForm = reactive({
  name: undefined,
  comment: undefined
})
const queryColumns: Columns = reactive([
  {
    label: '表名称',
    field: 'name',
    type: 'input',
    props: {
      placeholder: '请输入表名称',
    }
  },
  {
    label: '表备注',
    field: 'comment',
    type: 'input',
    props: {
      placeholder: '请输入表备注',
    }
  },
])


onBeforeMount(async () => {
  const dictStore = useDictStore();
  await dictStore.loadKeys(['form_type_enum', 'query_type_enum', 'query_form_type_enum']);

});

defineOptions({name: 'CodeGenerator'})

const GenPreviewModal = defineAsyncComponent(() => import('./GenPreviewModal.vue'))
//加载字典项


const {
  tableData: dataList,
  loading,
  pagination,
  search,
} = useTable((page) => getList({...queryForm, ...page}), {immediate: true})

const columns: TableInstanceColumns[] = [
  {
    title: '序号',
    width: 66,
    align: 'center',
    render: ({rowIndex}) => h('span', {}, rowIndex + 1 + (pagination.current - 1) * pagination.pageSize)
  },
  {title: '表名称', dataIndex: 'name', minWidth: 200, ellipsis: true, tooltip: true},
  {title: '表备注', dataIndex: 'comment', ellipsis: true, tooltip: true},
  {title: '引擎', dataIndex: 'engine', ellipsis: true, tooltip: true},
  {title: '版本号', dataIndex: 'version', width: 80},
  {title: '编码', dataIndex: 'collation', width: 150, ellipsis: true, tooltip: true},
  {title: '记录数', dataIndex: 'rows', ellipsis: true, tooltip: true},
  {title: '大小', dataIndex: 'data_length', ellipsis: true, tooltip: true},
  {title: '自增索引', dataIndex: 'auto_increment', width: 100},
  {title: '配置时间', dataIndex: 'create_time', width: 180},
  {title: '修改时间', dataIndex: 'update_time', width: 180},
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 250,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined
  },
]

// 重置
const reset = () => {
  queryForm.name = undefined
  queryForm.comment = undefined
  search()
}

const GenConfigDrawerRef = ref<InstanceType<typeof GenConfigDrawer>>()
// 配置
const onConfig = (tableName: string, comment: string) => {
  GenConfigDrawerRef.value?.onOpen(tableName, comment)
}

const GenPreviewModalRef = ref<InstanceType<typeof GenPreviewModal>>()
// 预览
const onPreview = (tableName: string) => {
  GenPreviewModalRef.value?.onOpen(tableName)
}

// 生成
const onGenerate = async (tableNames: string) => {
  const res = await generate(tableNames)
  const downloadElement = document.createElement('a')
  downloadElement.style.display = 'none'
  downloadElement.href = res.data.url
  // 下载后文件名
  downloadElement.download = res.data.download_name
  document.body.appendChild(downloadElement)
  // 点击下载
  downloadElement.click()
  // 下载完成，移除元素
  document.body.removeChild(downloadElement)
}
</script>

<style scoped lang="scss"></style>
